package cn.gov.mwr.szy206;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import cn.gov.mwr.szy206.command.UpCommand;
import cn.gov.mwr.szy206.utils.ByteUtil;
import cn.gov.mwr.szy206.utils.CrcUtil;

/**
 * 命令类，针对下发指令时所使用此类进行组装消息
 * 
 * @author admin
 *
 */
public class Command {

	protected byte upDown;

	private Command() {
	}

	public Command(byte upDown) {
		this();
		this.upDown = upDown;
	}

	public byte getUpDown() {
		return upDown;
	}

	public void setUpDown(byte upDown) {
		this.upDown = upDown;
	}

	protected IMessageHeader buildHeader(IMessageBody body) {
		// 报文头
		SzyMessageHeader header = new SzyMessageHeader();

		header.setBodySize(body.getLength());

		return header;
	}

	protected byte[] builderCrc(IMessage message) {

		byte[] crc = CrcUtil.crc8Check(message.getBody().getContent());

		return crc;

	}

	protected IMessage buildMessage(IMessageBody body) {

		try {
			IMessage message = new SzyMessage();
			message.setHeader(buildHeader(body));
			message.setBody(body);
			message.setCRC(builderCrc(message));
			message.setEOF(SzySymbol.EOF);
			return message;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 在这个方法中需要添加对ASC和HEX两种报文的转议
	 * 
	 * @param header
	 * @return
	 */
	public String toHexString(IMessageHeader header) {
		StringBuffer sb = new StringBuffer(header.getLength());
		sb.append(ByteUtil.toHexString(header.getStartBit()));
		sb.append(ByteUtil.toHexString(header.getBodySize()));
		sb.append(ByteUtil.toHexString(header.getBodyStartBit()));

		return sb.toString();
	}

	public String printHexString(IMessage message) {
		StringBuffer sb = new StringBuffer();
		sb.append(toHexString(message.getHeader()).toUpperCase());
		sb.append(ByteUtil.toHexString(message.getBody().getContent())
				.toUpperCase());
		sb.append(ByteUtil.toHexString(message.getCRC()).toUpperCase());
		sb.append(ByteUtil.toHexString(message.getEOF()).toUpperCase());

		return sb.toString();
	}

	public static void main(String[] args) {
		UpCommand cmd = new UpCommand();

//		IMessage message = cmd.sendMessage(null);
//
//		System.out.println(">> hex " + cmd.printHexString(message));
//
//		String hexStr = cmd.toHexString(message.getHeader());
//		System.out.print(">> hex " + hexStr.toUpperCase());
//		System.out.print(""
//				+ ByteUtil.toHexString(message.getBody().getContent()));
//		System.out.print("" + ByteUtil.toHexString(message.getEOF()));
//		System.out.print("" + ByteUtil.toHexString(message.getCRC()));
	}

}
